﻿using GedeaProject.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GedeaProject.Business
{
    public class FileStorageManager
    {
        private const string GenerationFolder = "Generated";
        private const string ApplicationFolder = "GedeaProyect";

        public void Store(string data, Company company)
        {
            string appFileRoot = GetAppFileRoot();

            if(!Directory.Exists(appFileRoot))
            {
                Directory.CreateDirectory(appFileRoot);
            }

            string fullAppFileName = string.Format("{0}\\{1}", appFileRoot, GetFileName(company));

            using (StreamWriter streamWriter = new StreamWriter(fullAppFileName))
            {
                streamWriter.Write(data);
            }

            //IML ruta configurable respecto al usuario. Al cambiarla que testee si tiene los permisos necesarios.
            //File.Copy(fileRoot + fileName, Credentials.DesktopRoot + fileName);

            File.SetAttributes(fullAppFileName, FileAttributes.ReadOnly);

            //TODO: Validar si se creo el archivo buscando si ahora existe. Sino, reventar.
        }

        private string GetAppFileRoot()
        {
            return string.Format("{0}\\{1}\\{2}\\{3}",
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    ApplicationFolder,
                    DateTime.Now.Year,
                    GenerationFolder);
        }

        private string GetFileName(Company company)
        {
            return string.Format("EBT_{0}_{1}_{2}_{3}_{4}_{5}_{6}.txt",
                    company.NameForBank.Replace(" ", "_"),
                    DateTime.Now.Year,
                    DateTime.Now.Month,
                    DateTime.Now.Day,
                    DateTime.Now.Hour,
                    DateTime.Now.Minute,
                    DateTime.Now.Second);
        }
    }
}
